package com.jsb.laundry.service.shops.impl;

import com.jsb.laundry.common.enums.BusinessType;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.dao.shops.WithdrawalDao;
import com.jsb.laundry.model.shops.CapitalAccount;
import com.jsb.laundry.model.shops.CapitalAccountUnstLog;
import com.jsb.laundry.model.shops.Withdrawals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
public class WithdrawalService {
    private static final Logger LOGGER = LoggerFactory.getLogger(WithdrawalService.class);
    @Autowired
    private WithdrawalDao withdrawalDao;

    /**
     * @param serialNum
     * @param accountId
     * @param type
     * @param remark
     * @param relatedNo
     * @param amount
     * @param businessType
     * @param deposit
     * @param depositFreeze
     * @param withdraw
     * @param withdrawFreeze
     * @param score
     * @param accountAmount
     * @return
     */
    @Transactional
    public int increase(
            String serialNum,
            String accountId,
            String type,
            String remark,
            String relatedNo,
            int amount,
            String businessType,
            int deposit,
            int depositFreeze,
            int withdraw,
            int withdrawFreeze,
            String score,
            int accountAmount
    ) {
        CapitalAccountUnstLog capitalAccountUnstLog = new CapitalAccountUnstLog();
        capitalAccountUnstLog.setSerialNum(serialNum);//流水号
        capitalAccountUnstLog.setAccountId(accountId);//账号id（capital_account表里的id）
        capitalAccountUnstLog.setType(type);//类型
        capitalAccountUnstLog.setRemark(remark);//备注
        capitalAccountUnstLog.setRelatedNo(relatedNo);//关联订单号
        capitalAccountUnstLog.setAmount(amount);//发生金额
        capitalAccountUnstLog.setBusinessType(businessType);//业务类型
        capitalAccountUnstLog.setDeposit(deposit);//可提现金额
        capitalAccountUnstLog.setDepositFreeze(depositFreeze);//待结算金额
        capitalAccountUnstLog.setWithdraw(withdraw);//提现金额
        capitalAccountUnstLog.setWithdrawFreeze(withdrawFreeze);//提现中金额
        capitalAccountUnstLog.setScore(score);//积分
        capitalAccountUnstLog.setAccountAmount(accountAmount);//账户余额
        int addResult = withdrawalDao.addCapitalAccountUnstLog(capitalAccountUnstLog);
        if (addResult == 0) {
            LOGGER.info("WithdrawalService:increase, instert failed, capitalAccountLog:{}", capitalAccountUnstLog);
        }
        return addResult;
    }

    /**
     * 资金业务处理 订单分账；根据订单号查出分账记录，按各角色进行分账，把待结算划转到待提现
     *
     * @param withdrawalNo 提现的单号
     * @param thirdpartId  用户id
     */
    @Transactional
    public void splitSettled(String withdrawalNo, String thirdpartId) {
        //查询用户账户的资金信息
        CapitalAccount userAccountInfo = withdrawalDao.capitalAccountInfo(thirdpartId, "2");
        //判断 资金账户不能未null
        if (userAccountInfo == null) {
            LOGGER.info("WithdrawalService:splitSettled, userAccountInfo is null, withdrawalNo:{}, thirdpartId:{}", withdrawalNo, thirdpartId);
            return;
        }
        // 查询用户提现记录
        Withdrawals userWithdrawaInfo = withdrawalDao.findByWithdrawalLogMoney(withdrawalNo);
        //系统账户分账开始---------------------------------------------
        //1 系统账户扣除用户提现金额到提现中
        CapitalAccount systemAccountInfo = withdrawalDao.capitalAccountInfo("jsb", "5");
        int systemOutResult = withdrawalDao.systemOut(userWithdrawaInfo.getAmount(), "1");
        if (systemOutResult == 0) {
            LOGGER.info("WithdrawalService:splitSettled, systemAccount update system deposit withdraw_freeze failed, withdrawalNo:{}, thirdpartId:{}, userWithdrawaInfo:{}, systemAccountInfo:{}", withdrawalNo, thirdpartId, userWithdrawaInfo, systemAccountInfo);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return;
        }
        //2 系统账户扣除用户提现金额到提现中 add unstlog
        systemAccountInfo = withdrawalDao.capitalAccountInfo("jsb", "5");
        int addSystemOutUnstLogResult= increase(JSBUtil.generateUUID(),"1","out","提现"+withdrawalNo,withdrawalNo,userWithdrawaInfo.getAmount(),
                String.valueOf(BusinessType.withdrawal),(int)systemAccountInfo.getDeposit(),(int)systemAccountInfo.getDepositFreeze(),(int)systemAccountInfo.getWithdraw(),(int)systemAccountInfo.getWithdrawFreeze(),
                systemAccountInfo.getScore(),(int)systemAccountInfo.getAccountAmount()
        );
        if (addSystemOutUnstLogResult == 0) {
            LOGGER.info("WithdrawalService:splitSettled, systemAccount add system deposit withdraw_freeze unstlog failed, withdrawalNo:{}, thirdpartId:{}, userWithdrawaInfo:{}, userAccountInfo:{}, systemAccountInfo:{}", withdrawalNo, thirdpartId, userWithdrawaInfo, userAccountInfo, systemAccountInfo);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return;
        }
        //3 用户账户扣除提现金额到提现中
        int userMoneyResult = withdrawalDao.userMoney(userWithdrawaInfo.getAmount(), userAccountInfo.getId());
        if (userMoneyResult == 0) {
            LOGGER.info("WithdrawalService:splitSettled, systemAccount update user deposit withdraw_freeze failed, withdrawalNo:{}, thirdpartId:{}, userWithdrawaInfo:{}, userAccountInfo:{}, systemAccountInfo:{}", withdrawalNo, thirdpartId, userWithdrawaInfo, userAccountInfo, systemAccountInfo);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return;
        }
        //4 用户账户扣除提现金额到提现中 add usntlog
        userAccountInfo = withdrawalDao.capitalAccountInfo(thirdpartId, "3");
        String userAccountInfoUserMoneySerialNumStr = JSBUtil.generateUUID();//流水号
        increase(userAccountInfoUserMoneySerialNumStr,userAccountInfo.getId(),"out","提现"+withdrawalNo,withdrawalNo,
                userWithdrawaInfo.getAmount(),String.valueOf(BusinessType.withdrawal),(int)userAccountInfo.getDeposit(),(int)userAccountInfo.getDepositFreeze(),(int)userAccountInfo.getWithdraw(),(int)userAccountInfo.getWithdrawFreeze(),
                userAccountInfo.getScore(),(int)userAccountInfo.getAccountAmount()
        );
        //5 用户账户扣除提现手续费
        int subUserWithdrawalFeeResult = withdrawalDao.subDepositAddDepositFreeze(userWithdrawaInfo.getCommissionAmount(), userAccountInfo.getId());
        if (subUserWithdrawalFeeResult == 0) {
            LOGGER.info("WithdrawalService:splitSettled, systemAccount update user deposit withdraw_commission_amount failed, withdrawalNo:{}, thirdpartId:{}, userWithdrawaInfo:{}, userAccountInfo:{}, systemAccountInfo:{}", withdrawalNo, thirdpartId, userWithdrawaInfo, userAccountInfo, systemAccountInfo);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return;
        }
        // 6 用户账户扣除提现手续费add unstlog
        userAccountInfo = withdrawalDao.capitalAccountInfo(thirdpartId, "3");
        increase(JSBUtil.generateUUID(),userAccountInfo.getId(),"out","提现服务费"+withdrawalNo,withdrawalNo,userWithdrawaInfo.getCommissionAmount(),
                String.valueOf(BusinessType.withdrawal_fee),(int)userAccountInfo.getDeposit(),(int)userAccountInfo.getDepositFreeze(),(int)userAccountInfo.getWithdraw(),(int)userAccountInfo.getWithdrawFreeze(),
                userAccountInfo.getScore(),(int)userAccountInfo.getAccountAmount()
        );
        //7 系统账户增加提现手续费到待结算
        systemAccountInfo = withdrawalDao.capitalAccountInfo("jsb", "5");
        int systemInResult = withdrawalDao.systemIn(userWithdrawaInfo.getCommissionAmount(), systemAccountInfo.getId());
        if (systemInResult == 0) {
            LOGGER.info("WithdrawalService:splitSettled, systemAccount in withdrawFee to deposit_freeze failed, withdrawalNo:{}, thirdpartId:{}, userWithdrawaInfo:{}, userAccountInfo:{}, systemAccountInfo:{}", withdrawalNo, thirdpartId, userWithdrawaInfo, userAccountInfo, systemAccountInfo);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return;
        }
        //8 系统账户增加提现手续费到待结算add unstlog
        systemAccountInfo = withdrawalDao.capitalAccountInfo("jsb", "5");
        int addSystemInUnstLogResult= increase(JSBUtil.generateUUID(),systemAccountInfo.getId(),"in","提现手续费"+withdrawalNo,withdrawalNo,userWithdrawaInfo.getCommissionAmount(),
                String.valueOf(BusinessType.withdrawal_fee),(int)systemAccountInfo.getDeposit(),(int)systemAccountInfo.getDepositFreeze(),(int)systemAccountInfo.getWithdraw(),(int)systemAccountInfo.getWithdrawFreeze(),
                systemAccountInfo.getScore(),(int)systemAccountInfo.getAccountAmount()
        );
        if (addSystemInUnstLogResult == 0) {
            LOGGER.info("WithdrawalService:splitSettled, systemAccount in withdrawFee to deposit_freeze unstlog  failed, withdrawalNo:{}, thirdpartId:{}, userWithdrawaInfo:{}, userAccountInfo:{}, systemAccountInfo:{}", withdrawalNo, thirdpartId, userWithdrawaInfo, userAccountInfo, systemAccountInfo);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return;
        }
    }

}
